const Friend = require('../models/Friend');
const User = require('../models/User');

// 添加好友
exports.addFriend = async (req, res) => {
    try {
        const { userId } = req.body;

        // 确保 user1 是当前登录用户，user2 是目标用户
        const user1 = req.user.id;
        const user2 = userId;

        // 检查是否已经是好友
        const existingFriend = await Friend.findOne({ 
            $or: [
                { user1, user2 },
                { user1: user2, user2: user1 }
            ]
        });

        if (existingFriend) {
            return res.status(400).json({ message: '好友请求已存在' });
        }

        const newFriend = await Friend.create({
            user1,
            user2,
            status: 'pending' // 默认状态为待接受
        });

        res.status(201).json({ message: '好友请求发送成功', data: newFriend });
    } catch (error) {
        console.error('添加好友失败:', error);
        res.status(500).json({ message: '添加好友失败', error });
    }
};

// 接受好友请求
exports.acceptFriend = async (req, res) => {
  const { id } = req.params;
  const userId = req.user._id;

  try {
    const friend = await Friend.findById(id);
    if (!friend || friend.user2.toString() !== userId.toString()) {
      return res.status(404).json({ message: 'Friend request not found' });
    }

    friend.status = 'accepted';
    await friend.save();
    res.status(200).json(friend);
  } catch (error) {
    res.status(500).json({ message: 'Error accepting friend request', error });
  }
};

// 拒绝好友请求
exports.rejectFriend = async (req, res) => {
  const { id } = req.params;
  const userId = req.user._id;

  try {
    const friend = await Friend.findById(id);
    if (!friend || friend.user2.toString() !== userId.toString()) {
      return res.status(404).json({ message: 'Friend request not found' });
    }

    friend.status = 'rejected';
    await friend.save();
    res.status(200).json(friend);
  } catch (error) {
    res.status(500).json({ message: 'Error rejecting friend request', error });
  }
};

// 删除好友
exports.deleteFriend = async (req, res) => {
  const { id } = req.params;
  const userId = req.user._id;

  try {
    const friend = await Friend.findById(id);
    if (!friend || (friend.user1.toString() !== userId.toString() && friend.user2.toString() !== userId.toString())) {
      return res.status(404).json({ message: 'Friend not found' });
    }

    await friend.remove();
    res.status(200).json({ message: 'Friend deleted' });
  } catch (error) {
    res.status(500).json({ message: 'Error deleting friend', error });
  }
};

// 获取好友列表
exports.getFriends = async (req, res) => {
  const userId = req.user._id;

  try {
    const friends = await Friend.find({
      $or: [
        { user1: userId, status: 'accepted' },
        { user2: userId, status: 'accepted' }
      ]
    }).populate('user1 user2');
    res.status(200).json(friends);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching friends', error });
  }
};